/*
 * Copyright (c) 2012 swing-on-fire Team
 * 
 * This file is part of Swing-On-Fire (http://code.google.com/p/swing-on-fire), licensed under the terms of the MIT
 * License (MIT).
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
 * Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
package com.google.code.swingonfire.utility;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Reflection
{

    private enum Match
    {
        NONE,
        CONVERTABLE,
        ASSIGNABLE,
        BOXED,
        EXACT;

        public boolean isBetterThan(Match match)
        {
            return ordinal() > match.ordinal();
        }

        public Match combine(Match match)
        {
            if (ordinal() < match.ordinal())
            {
                return this;
            }

            return match;
        }
    }

    public static Class<?> typeOf(Object object)
    {
        return (object != null) ? object.getClass() : Void.TYPE;
    }

    public static Class<?>[] typesOf(Object[] objects)
    {
        Class<?>[] results = new Class<?>[objects.length];

        for (int i = 0; i < objects.length; i += 1)
        {
            results[i] = typeOf(objects[i]);
        }

        return results;
    }

    /**
     * Returns the non-primitive representation of the class
     * 
     * @param type the class, may be null
     * @return the non-primitive alternative or null
     */
    public static Class<?> cultivate(final Class<?> type)
    {
        if (type == null)
        {
            return null;
        }

        if (!type.isPrimitive())
        {
            return type;
        }

        if (type == Integer.TYPE)
        {
            return Integer.class;
        }

        if (type == Boolean.TYPE)
        {
            return Boolean.class;
        }

        if (type == Double.TYPE)
        {
            return Double.class;
        }

        if (type == Long.TYPE)
        {
            return Long.class;
        }

        if (type == Character.TYPE)
        {
            return Character.class;
        }

        if (type == Float.TYPE)
        {
            return Float.class;
        }

        if (type == Byte.TYPE)
        {
            return Byte.class;
        }

        if (type == Short.TYPE)
        {
            return Short.class;
        }

        return type;
    }

    @SuppressWarnings("unchecked")
    public static <TYPE> Constructor<TYPE> findConstructor(Class<TYPE> type, Class<?>... parameterTypes)
    {
        Constructor<?> constructor = null;
        Match match = Match.NONE;

        for (Constructor<?> currentConstructor : type.getConstructors())
        {
            Match currentMatch = matches(currentConstructor.getParameterTypes(), parameterTypes);

            if (currentMatch.isBetterThan(match))
            {
                constructor = currentConstructor;
                match = currentMatch;
            }
        }

        return (Constructor<TYPE>) constructor;
    }

    public static <TYPE> TYPE invokeConstructor(Constructor<TYPE> constructor, Object... parameters)
    {
        try
        {
            return constructor.newInstance(parameters);
        }
        catch (InstantiationException e)
        {
            throw new IllegalArgumentException("Failed to invoke " + constructor, e);
        }
        catch (IllegalAccessException e)
        {
            throw new IllegalArgumentException("Failed to access " + constructor, e);
        }
        catch (IllegalArgumentException e)
        {
            throw new IllegalArgumentException("Failed to invoke " + constructor, e);
        }
        catch (InvocationTargetException e)
        {
            throw new IllegalArgumentException("Failed to invoke " + constructor, e);
        }
    }

    public static <TYPE> Method findMethod(Class<TYPE> type, String name, Class<?>... parameterTypes)
    {
        Method method = null;
        Match match = Match.NONE;

        for (Method currentMethod : type.getMethods())
        {
            if (!name.equalsIgnoreCase(currentMethod.getName()))
            {
                continue;
            }

            Match currentMatch = matches(currentMethod.getParameterTypes(), parameterTypes);

            if (currentMatch.isBetterThan(match))
            {
                method = currentMethod;
                match = currentMatch;
            }
        }

        return method;
    }

    public static <TYPE> Object invokeMethod(Method method, Object object, Object... parameters)
    {
        try
        {
            return method.invoke(object, parameters);
        }
        catch (IllegalAccessException e)
        {
            throw new IllegalArgumentException("Failed to access " + method, e);
        }
        catch (IllegalArgumentException e)
        {
            throw new IllegalArgumentException("Failed to invoke " + method, e);
        }
        catch (InvocationTargetException e)
        {
            throw new IllegalArgumentException("Failed to invoke " + method, e);
        }
    }

    private static Match matches(Class<?>[] types, Class<?>[] otherTypes)
    {
        // TODO add support for varargs

        if (types.length != otherTypes.length)
        {
            return Match.NONE;
        }

        Match match = Match.EXACT;

        for (int i = 0; i < types.length; i += 1)
        {
            if (types[i] == otherTypes[i])
            {
                match = match.combine(Match.EXACT);
                continue;
            }

            Class<?> type = cultivate(types[i]);
            Class<?> otherType = cultivate(otherTypes[i]);

            if (type == otherType)
            {
                match = match.combine(Match.BOXED);
                continue;
            }

            if (types[i].isAssignableFrom(otherTypes[i]))
            {
                match = match.combine(Match.ASSIGNABLE);
                continue;
            }

            if (TypeConversion.isConvertable(otherType, type))
            {
                match = match.combine(Match.CONVERTABLE);
                continue;
            }

            return Match.NONE;
        }

        return match;
    }
}
